package com.platform.common.util;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-9-12
 * Time: 下午4:38
 * To change this template use File | Settings | File Templates.
 */
public class SqlUtil {

    /**
     * 定位SQL语句select元素位置
     * @param querySql 查询SQL语句
     * @return SQL语句
     */
    public static int getAfterSelectPoint(String querySql) {
        int minLen = "select".length();
        int len = "select distinct".length();
        int selectIndex = querySql.toLowerCase().indexOf("select");
        final int selectDistinctIndex = querySql.toLowerCase().indexOf("select distinct");
        return selectIndex + (selectDistinctIndex == selectIndex ? len : minLen);
    }

    /**
     * 定位SQL语句Form元素位置
     * @param querySql 查询SQL语句
     * @return SQL语句
     */
    public static int getAfterFormPoint(String querySql) {
        int formIndex = querySql.toLowerCase().indexOf("from");
        return formIndex;
    }

    /**
     * 将SQL语句包装成查询记录总数的SQL
     * @param querySql SQL语句
     * @return SQL语句
     */
    public static String getCountString(String querySql) {
        String sql = new StringBuffer(querySql.length() + 22)
                .append(querySql.substring(0, getAfterSelectPoint(querySql) + 1))
                .append("count(1) AS rowCount")
                .append(querySql.substring(getAfterFormPoint(querySql) - 1, querySql.length()))
                .toString();
        return sql;
    }
}
